package bank;

public class _43MultiplyStr {
    public static String multiply(String num1, String num2) {
        if (num1.equals("0")){
            return "0";
        }
        //  因为num的长度远超过了int的范围，故无法使用 Integer.parseInt() 方法
        //  方法：竖式相乘
        String res = "";
        //  先写一个方法，计算字符串相加
        //  addStr(num1,num2);
        //  再写一个方法，计算字符串与单个字符相乘
        //  multiStrAndChar(num1,num2.charAt(0));
        char[] chars2 = num2.toCharArray();
        for (int i = chars2.length-1;i >= 0;i--){
            StringBuilder stringBuilder = new StringBuilder(multiStrAndChar(num1,chars2[i]));
            stringBuilder.append("0".repeat(Math.max(0, chars2.length - 1 - i)));
            res = addStr(res,stringBuilder.toString());
        }
        return res;
    }

    private static String multiStrAndChar(String num, char charAtI) {
        if (charAtI == '0'){
            return "0";
        }
        String string = new String(num);
        int charI = charAtI - '0';
        for (int i = 1;i < charI;i++){
            string = addStr(string,num);
        }
        return string;
    }

    private static String addStr(String num1, String num2) {
        StringBuilder stringBuilder = new StringBuilder();
        int len1 = num1.length(), len2 = num2.length();
        int adv = 0;
        for (int i = 0;i < Math.min(len1,len2);i++){
            int num01 = num1.charAt(len1-i-1) - '0';
            int num02 = num2.charAt(len2-i-1) - '0';
            stringBuilder.insert(0,(num01+num02+adv) % 10);
            adv = adv + num01 + num02 > 9 ? 1 : 0;
        }
        String remain = len1 > len2 ? num1 : num2;
        if (adv == 0){
            //  没有进位就把更长串的剩下元素直接插入到
            stringBuilder.insert(0,remain.substring(0,Math.abs(len1-len2)));
        }else if (len1 != len2){
            //  如果有进位则需要考虑新的进位问题
            for (int i = Math.abs(len1-len2)-1;i >= 0;i--){
                int num = remain.charAt(i) - '0';
                stringBuilder.insert(0,(num + adv) % 10);
                adv = adv + num > 9 ? 1 : 0;
            }
        }
        if (adv == 1){
            stringBuilder.insert(0,1);
        }
        return stringBuilder.toString();
    }
}
